﻿using B.S.BasicData.Api.Read.Application.Command.Approval;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity.Approval;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using B.S.BasicData.Infastructure.Migrations;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Api.Read.Application.Handler.Approval
{
    public class GetApprovalListHandler : IRequestHandler<GetApprovalListCommand, ApiPaging<ApprovalListDto>>
    {
        private readonly IBaseRepository<UsersModel> _userRepository;
        private readonly IBaseRepository<DeparmentModel> _DeparmentRepository;
        private readonly IBaseRepository<ApprovalModel> _approvalRepository;
        private readonly IBaseRepository<LeaveTypeModel> _leaveRepository;

        public GetApprovalListHandler(IBaseRepository<UsersModel> userRepository, IBaseRepository<DeparmentModel> deparmentRepository, 
            IBaseRepository<ApprovalModel> approvalRepository, IBaseRepository<LeaveTypeModel> leaveRepository)
        {
            _userRepository = userRepository;
            _DeparmentRepository = deparmentRepository;
            _approvalRepository = approvalRepository;
            _leaveRepository = leaveRepository;
        }
        /// <summary>
        /// 获取审批列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<ApprovalListDto>> Handle(GetApprovalListCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<ApprovalListDto>result = new ApiPaging<ApprovalListDto>();

            //根据登录人Id查出用户信息 id,名称,部门Id
            var UserInfo =_userRepository.GetAll().Where(p=>p.Id==request.UserId).Select(p=>new 
            { p.Id,p.UserName,p.DeparmentId }).FirstOrDefault();

            //再根据部门Id查所在的部门信息 id,领导人,部门名称
            var deparment = _DeparmentRepository.GetAll().Where(p => p.Id == UserInfo.DeparmentId).Select(p => new
            { p.Id, p.Header, p.DeparmentName }).FirstOrDefault();

            if (UserInfo == null || deparment == null)
            {
                result.Message = "用户或部门信息不存在";
                result.TotalCount = 0;
                return Task.FromResult(result);
            }

            //如果登录人==部门领导人名称  
            bool IsLeader = (UserInfo.UserName == deparment.Header);

            var approval = _approvalRepository.GetAll().Where(p=>p.IsDelete==false);//申请单数据
            var lavetypelist = _leaveRepository.GetAll();
            var deparmentlist = _DeparmentRepository.GetAll();
            var userlist = _userRepository.GetAll();

            //如果登录人==部门领导 则查同部门下的所有请假信息
            if (IsLeader)
            {
                approval = approval.Where(c => c.Approvaler==UserInfo.UserName);
            }
            //如果不是部门领导 则只查用户自己的
            else
            {
                approval = approval.Where(p => p.UserId == UserInfo.Id);
            }
            

            var query = from a in approval  
                        join u in userlist on a.UserId equals u.Id  
                        join d in deparmentlist on a.DeparmentId equals d.Id  
                        join l in lavetypelist on a.LeaveType equals l.Id  
                        select new ApprovalListDto
                        {
                            Id = a.Id,
                            UserId = a.UserId,
                            UserName = u.UserName,
                            DeparmentId = a.DeparmentId,
                            DeparmentName = d.DeparmentName,
                            LeaveType = a.LeaveType,
                            LeaveTypeName = l.LeaveName,
                            Status = a.Status,  
                            Reason = a.Reason,
                            StartTime = a.StartTime,
                            YeNo=a.YeNo,
                            EndTime = a.EndTime,
                            ReportTime=a.EndTime,
                            Hours = a.Hours,
                            Approvaler = a.Approvaler,
                            Remark = a.Remark,
                            CreateTime = (DateTime)a.CreateTime  
                        };

            if(!string.IsNullOrEmpty(request.UserName))
            {
                query = query.Where(p => p.UserName.Contains(request.UserName));
            }
            if (request.StartTime != null)
            {
                query = query.Where(p => p.StartTime >= request.StartTime);
            }

            if (request.EndTime != null)
            {
                query = query.Where(p => p.EndTime <= request.EndTime);
            }
            if (request.Status!=null)
            {
                query = query.Where(p => p.Status == request.Status.Value);
            }
            result.TotalCount= query.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pagesize);
            result.PageData=query.OrderByDescending(p=>p.Id).Skip((request.pageindex-1)*request.pagesize).Take(request.pagesize).ToList();
            result.Message = "查询成功";
            return Task.FromResult(result);
        }
    }
}
